package com.xyg.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.xyg.auth.Role;
import com.xyg.dao.UserRepository;
import com.xyg.pojo.User;
import com.xyg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User save ( User user ) {
        String hashedPassword = BCrypt.hashpw( user.getPassword(), BCrypt.gensalt() );
        user.setPassword( hashedPassword );
        if ( user.getRole() == null ) user.setRole( Role.USER );
        user.setId( null );
        return userRepository.save( user );
    }

    @Override
    public Optional< User > findByUsername ( String username ) {
        return userRepository.findByUsername( username );
    }

    @Override
    public Optional< User > findById ( String id ) {
        return userRepository.findById( id );
    }

    @Override
    public List< User > findAll () {
        return userRepository.findAll();
    }

    @Override
    public User updateById ( String id, User userDetails ) {
        return userRepository.findById( id )
                .map( existingUser -> {
                    if ( userDetails.getUsername() != null ) existingUser.setUsername( userDetails.getUsername() );
                    if ( userDetails.getEmail() != null ) existingUser.setEmail( userDetails.getEmail() );
                    if ( userDetails.getRole() != null ) existingUser.setRole( userDetails.getRole() );
                    return userRepository.save( existingUser );
                } ).orElseThrow( () -> new RuntimeException( "未找到 ID 为: " + id + " 的用户" ) );
    }

    @Override
    public void deleteById ( String id ) {
        if ( userRepository.existsById( id ) ) {
            userRepository.deleteById( id );
        } else {
            throw new RuntimeException( "未找到 ID 为: " + id + " 的用户" + id );
        }
    }

    @Override
    public boolean authenticate ( User user ) {
        Optional< User > userOptional = userRepository.findByUsername( user.getUsername() );
        if ( userOptional.isPresent() ) {
            User hasUser = userOptional.get();
            return BCrypt.checkpw( user.getPassword(), hasUser.getPassword() );
        }
        return false;
    }
}
